package v1

import (
	"net/http"
	"toy-car/models"
	"toy-car/pkg/e"
	"toy-car/pkg/util"

	"github.com/gin-gonic/gin"
	"github.com/unknwon/com"
)

type IdsReq struct {
	Ids []int `json:"ids" form:"ids"`
}

func ApiAdd(c *gin.Context) {
	var api models.SysApi
	_ = c.ShouldBindJSON(&api)

	data := make(map[string]interface{})
	code := e.SUCCESS
	if err := models.CreateApi(api); err != nil {
		code = e.ERROR
	}

	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  e.GetMSG(code),
		"data": data,
	})
}

func GetApiList(c *gin.Context) {
	page, pageSize := util.GetPageAndSize(c)
	var api models.SysApi
	_ = c.ShouldBindQuery(&api)

	data := make(map[string]interface{})
	code := e.SUCCESS
	list, total, err := models.GetAPIInfoList(api, page, pageSize, "id", true)
	if err != nil {
		code = e.ERROR
	}
	data["page"] = page
	data["pageSize"] = pageSize
	data["data"] = list
	data["total"] = total
	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  e.GetMSG(code),
		"data": data,
	})
}

func GetApiInfo(c *gin.Context) {
	id := com.StrTo(c.Param("id")).MustInt()
	user, err := models.GetApiById(id)

	code := e.SUCCESS
	if err != nil {
		code = e.ERROR
	}

	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  e.GetMSG(code),
		"data": user,
	})
}

func ApiUpdate(c *gin.Context) {
	uid := com.StrTo(c.Param("id")).MustInt()
	var api models.SysApi
	_ = c.ShouldBindJSON(&api)
	api.ID = uid

	err := models.UpdateApi(api)
	data := make(map[string]interface{})
	code := e.SUCCESS
	if err != nil {
		code = e.ERROR
	}

	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  e.GetMSG(code),
		"data": data,
	})
}

func ApiDelete(c *gin.Context) {
	id := com.StrTo(c.Param("id")).MustInt()

	data := make(map[string]interface{})
	code := e.SUCCESS

	// todo 比对删除自己，返回错误
	err := models.DeleteApi(id)
	if err != nil {
		code = e.ERROR
	}

	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  e.GetMSG(code),
		"data": data,
	})
}

func MultiApiDelete(c *gin.Context) {
	var ids IdsReq
	err := c.ShouldBindJSON(&ids)
	data := make(map[string]interface{})
	code := e.SUCCESS
	if err != nil {
		code = e.ERROR
	}
	err = models.DeleteApisByIds(ids.Ids)
	if err != nil {
		code = e.ERROR
	}
	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  e.GetMSG(code),
		"data": data,
	})
}
